package top.rainf.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.rainf.support.Result;
import top.rainf.util.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 星环
 * @date 2023/5/24 2:26:46
 * @description 图片控制器类，管上传图片
 */
@Slf4j
@RestController
@RequestMapping("/image")
public class ImageController {

    /**
     * 上传头像，目前还是坏的，因为tomcat缓存目录找不到。。文件要复制进项目部署目录一份
     * @param request
     * @param response
     * @param file 上传的文件
     * @return
     */
    @RequestMapping("/uploadAvatar")
    public Result uploadAvatar(HttpServletRequest request,HttpServletResponse response,
                               @RequestParam(value = "avatar",required = false) MultipartFile file){
        //返回的url
        String url = null;
        if(!file.isEmpty()){
            try {
                //保存文件到指定目录，添加随机后缀。
                url = FileUtil.saveFileTo(file, FileUtil.avatarImageSavePath, FileUtil.getRandomSuffix(),request);

                return Result.success().addObj("url",url);
            }catch (Exception e){e.printStackTrace();
            }
        }
        return Result.fail();

    }

    @RequestMapping("uploadPostImage")
    public Result uploadPostImage(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "editormd-image-file",required = false)MultipartFile file){
        String url = null;
        if(!file.isEmpty()){
            try {
                url = FileUtil.saveFileTo(file, FileUtil.postImageSavePath, FileUtil.getRandomSuffix(), request);

                return Result.success().addObj("success",1).addObj("message","上传成功").addObj("url",url);
            }catch (Exception e){e.printStackTrace();
            }
        }
        return Result.fail().addObj("success",0).addObj("message","上传失败");

    }
}
